<template>
  <div id="app">
      <div class="context" ref="context">
        <div class="dataBox" style="height:100%;border:0px solid red;">
          <el-row>
            <el-col :span="12" :offset="6">
              <div>
                <!--  :data="treeData" -->
                <el-tree
                  node-key="id"
                  ref="tree" 
                  lazy
                  show-checkbox
                  :expand-on-click-node="false" 
                  :props="props1"
                  :load="loadNode1"
                  >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span>
                      <!-- <el-button
                      v-permission="{menuCode: menuCode,resourceCode: 'saveBtnText'}"
                        type="text"
                        size="mini"
                        @click="() => append(node, data,'saveBtnText')">
                        新增
                      </el-button> -->
                      <!-- <el-button
                      v-permission="{menuCode: menuCode,resourceCode: 'editBtnText'}"
                        type="text"
                        size="mini"
                        @click="() => edit(data,this,'editBtnText')">
                        编辑
                      </el-button> -->
                      <!-- <el-button
                       v-permission="{menuCode: menuCode,resourceCode: 'sendBtnText'}"
                        type="text"
                        size="mini"
                        @click="() => onSend(data,'sendBtnText')">
                        下发
                      </el-button> -->
                      
                      <!-- @click="() => remove(node, data)" -->
                      <!-- <el-button
                       v-permission="{menuCode: menuCode,resourceCode: 'deleteBtnText'}"
                        type="text"
                        size="mini"
                        @click="() => logoffRow(node, data,'deleteBtnText')">
                        删除
                      </el-button> -->
                    </span>
                  </span>
                </el-tree>
              </div>
            </el-col>

          </el-row>


        </div>


      <!--编辑对话框-->
        <el-dialog :title="$t('label.dialogTitle')"  :visible.sync="isShowEditForm"  top="5vh" @close="refresh">
            <el-form :model="editForm" ref="editForm" size="mini"
                      status-icon=status-icon :rules="editRules">
                <el-form-item :label="$t('editLabel.capital.classifyName')"  prop="capitalName" :label-width="editformLabelWidth">
                    <el-input v-model.trim="editForm.capitalName"
                              :placeholder="$t('editLabel.capital.placeholderClassifyName')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('editLabel.capital.identifier')"  prop="capitalCode" :label-width="editformLabelWidth">
                    <el-input v-model.trim="editForm.capitalCode" :placeholder="$t('editLabel.capital.placeholderIdentifier')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('editLabel.capital.classificationInstructions')"  prop="isEnable" :label-width="editformLabelWidth">
                     <el-select v-model="editForm.isEnable" placeholder="请选择">
                        <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                        <!-- <el-option :label="$t('label.available')" value="Available"></el-option>
                        <el-option :label="$t('label.invalid')" value="Invalid"></el-option> -->
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isShowEditForm = false" >{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="submitForm('editForm',currentResCode)" >{{ $t('btnText.saveBtnText') }}</el-button>
            </div>
        </el-dialog>

        <!-- 下发对话框 -->
        <el-dialog :title="$t('下发')" :visible.sync="isSendEditForm" top="5vh" @close="refresh">
            <el-form :inline="true" :model="sendForm" ref="sendForm" size="mini"
                     :label-position="editFormPosition" status-icon=status-icon :rules="sendRules">

            <el-row>
                <el-form-item :label="$t('')" :label-width="editformLabelWidth" prop="siteList">
                    <el-checkbox-group v-model="sendForm.siteList" >
                        <el-checkbox :value="item.siteName" :key="item.keyId" :label="item.keyId" v-for="item in siteData">{{item.siteName}}</el-checkbox>
                    </el-checkbox-group> 
                </el-form-item>
            </el-row>

            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isSendEditForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="comfirmSend('sendForm',currentResCode)" :loading="loading">{{ $t('btnText.sendConfirmBtnText') }}</el-button>
            </div>

        </el-dialog>

      </div>

  </div>
</template>

<script>
let id = 1000;
import comBaseVue from "../../baseViewModel";

export default {
  mixins: [comBaseVue],
  props:{
    menuCode:String
  },
  data() {
    const data = [
        {
          id: 1,
          label: "资产分类",
          // children: [
          //   {
          //     id: 4,
          //     label: "电影",
          //     children: [
          //       {
          //         id: 9,
          //         label: "地区",
          //         children: [
          //           {
          //             id: 11,
          //             label: "武汉"
          //           },
          //           {
          //             id: 12,
          //             label: "郑州"
          //           }
          //         ]
          //       },
          //       {
          //         id: 10,
          //         label: "内容",
          //         children: [
          //           {
          //             id: 13,
          //             label: "最新上线"
          //           }
          //         ]
          //       }
          //     ]
          //   }
          // ]
        }
      ];
    return {
      nodeId:null,
      props1: {
          id: "id",
          label: 'label',
          children: 'children',
          isLeaf: 'leaf'
        },
      loading: false,
      isSendEditForm: false,
      enables: [],
      tableData: [],
      tableHeight: 100,
       appDivStyle:{
            height:this.$store.getters.appHeight,
        },
      modelName: "com.ispr.iptv.entity.media.CapitalEntity",
      data4: data,
      data5: data,
      columns:[
        {
          label:"分类名称",
          prop: "label",
          minWidth: "200px"
        },
        {
          label:"操作",
          prop: "id",
          minWidth: "150px",
          type: 'template',
          template: 'id',
        }
        ],


      // 编辑面板绑定的对象
      editForm: {
        keyId: 0,
        version: 0,
        capitalCode: "",
        capitalName: "",
        sendtoState: "",
        pCapitalCode: "",
        sort: 0,
        isEnable: "",
        // classificationInstructions: ""
      },
      // 编辑面板的验证规则
      editRules: {
        capitalCode: [
          {
            required: true,
            message: this.$i18n.t("Capital.rules.placeholderCapitalCode"),
            trigger: "blur"
          }
        ],
        capitalName: [
          {
            required: true,
            message: this.$i18n.t("Capital.rules.placeholderCapitalName"),
            trigger: "blur"
          }
        ]
      },
      auditForm:{

      },
      auditRules:{

      },
      treeData:[],
      subData:[],
      // 树控件
      menuTreeData: [],
      selectRowID: "",
      defaultProps: {
        children: "childs",
        label: "menuName"
      },
      current: {
        row: {},
        node: {}
      },
      //下发
      siteData:[],
      singleSend:{},
      sendForm: {
          siteList: [],//下发到的站点
          sendType:"",
      },
      sendRules: {
          siteList: [{ required: true, message: this.$i18n.t('ParentAssetIssuance.rules.sendCheckTip'), trigger: 'blur' }],
      },

    };
  },

  methods: {

    loadNode1(node, resolve) {
        let _this = this;
      // console.log(node, resolve);
        if (node.level === 0) {
          return resolve([{ label: '资产分类',id:'root' }]);
        }
        
        if (node.level >= 1) {
            let requestArgs = {
                commandCode: "QueryTreeDataProc",
                className: "com.ispr.iptv.entity.media.CapitalEntity",
                commandArgs: "Default",
                commandBody: { "pCapitalCode":node.data.id},
                params: null,
                userInfo: this.getUserInfo()
            };
            
            this.axios.post('/api/execute', requestArgs)
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.treeData = [];
                        _this.treeData = res.data.data;
                        return resolve(_this.treeData);
                    } else {
                        _this.setTableData.call(_this, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.setTableData.call(_this, false, "serverError");
                });



        }

      },

    setNodeData (node) {
      this.procCommand("QueryTreeDataProc",
          "com.ispr.iptv.entity.media.CapitalEntity",
          "Default",
          {
            "pCapitalCode":node.data.id,
          },
          null,
          this.setDataCallback);
    },

    // 新增
    append: function append(node, data,rescode) {

      console.log("append(data)==>",data);
      console.log("append(node)==>",node);
      //alert(node.id);
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      this.nodeId = data;
      this.isShowEditForm = true;
      // let id = 9000;
      // const newChild = { id: id++, label: this.editForm.capitalName, children: [] };
      // if (this.$refs["editForm"]) {
      //   this.$refs["editForm"].resetFields();
      // }
      // if (!data.children) {
      //   this.$set(data, "children", []);
      // }
      // data.children.push(newChild);

      this.editForm.keyId = "";
      this.editForm.version = "";
      this.editForm.capitalCode = "",
      this.editForm.capitalName = "",
      this.editForm.sendtoState = "StayDown",
      this.editForm.pCapitalCode = data.id;
      this.editForm.sort = 0;
      this.editForm.isEnable = "Available";
      this.curCommand = "SaveNewReturnPK";
    },
     // 提交编辑面板数据
    submitForm: function submitForm(formName) {
        var _this = this;
        this.setEditFormCheck();

        this.$refs[formName].validate(function (valid) {
            if (valid) {
                _this.loading = true;
                _this.procCommand(_this.curCommand,
                _this.modelName,
                "Default",
                _this.editForm,
                _this.editFormCheck,
                _this.submitFormCallback);
            } else {
                return false;
            }
        });
        //this.queryTable();
         // const newChild = { id: id++, label: this.editForm.capitalName, children: [] };
        // if (!data.children) {
        //   this.$set(data, 'children', []);
        // }
        // data.children.push(newChild);
    },

    submitFormCallback: function submitFormCallback(isSuccess,json) {
            this.loading = false;
            if(isSuccess){
                this.isShowEditForm = false;
                this.$message({
                    message: this.$i18n.t("message.successTip"),//resource.message.successTip,
                    type: 'success'
                });
                //_this.$refs.tree.getNode(_this.nodeId)
                console.log("append(node2)==>",this.$refs.tree.getNode(this.nodeId));
                //this.$refs.tree.getNode(this.nodeId).childNodes = [];
            let requestArgs = {
                commandCode: "QueryTreeDataProc",
                className: "com.ispr.iptv.entity.media.CapitalEntity",
                commandArgs: "Default",
                commandBody: { "pCapitalCode":this.nodeId.id},
                params: null,
                userInfo: this.getUserInfo()
            };
            let _this =  this;
            this.axios.post('/api/execute', requestArgs)
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        var theChildren = _this.$refs.tree.getNode(_this.nodeId).childNodes;
                        theChildren.splice(0, theChildren.length);
                        console.info("_this.treeData==>", _this.treeData);
                        _this.$refs.tree.getNode(_this.nodeId).doCreateChildren(res.data.data);
                    } else {
                        _this.setTableData.call(_this, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.setTableData.call(_this, false, "serverError");
                });

                //this.queryTable();
            }
            else
            {
                this.$message({
                                message: json.msg,
                                type: 'warning'
                                });
            }
        },

    edit: function(row, node){
      // console.info(row);
      // console.info(row.children);
      //row.children = [];
      if(row.id=="root"){
        this.$message.warning("该根节点数据不允许编辑");
        return;
      }
      this.isShowEditForm = true;
      this.queryModelByKeyID(this.modelName,row.id,"byId",this.editCallback);
    },

     // 编辑按钮回调事件
    editCallback: function(isSuccess,json) {
        if(isSuccess){
            this.curCommand = "PartialUpdateProc";
            this.isShowEditForm = true;
            if (this.$refs['editForm']) {
                this.$refs['editForm'].resetFields();
            }
            this.editForm = json;

            // this.canEditCode = true;
        }
        else{
            this.$message({
                message: json.msg,
                type: 'warning'
                });
        }
    },

   // 注销按钮
        // logoffRow: function(row) {
        //   // alert(12);
        //     var _this = this;
        //     this.$confirm(this.$i18n.t("message.confirmlogoffMessage"),
        //         this.$i18n.t("message.confirmTitle"), {
        //         confirmButtonText: this.$i18n.t("message.yes"),
        //         cancelButtonText: this.$i18n.t("message.cancel"),
        //         type: "warning",
        //         callback: function (action, instance) {
        //             if (action == "confirm") {
        //                 var commandBody = {  "keyId":row.id, "version": 1, isEnable: "Invalid" };
        //                 // var commandBody = {
        //                 //     data: [{ keyID: row.keyID, ver: row.version }],
        //                 //     val: "Invalid",
        //                 //     count: 1
        //                 // };
        //                 _this.loading = true;
        //                 _this.procCommand("PartialUpdateProc",//"ChangeIsEnabledState",
        //                         _this.modelName,
        //                         "N",
        //                         commandBody,
        //                         null,
        //                         _this.submitFormCallback);
        //             }

        //         }
        //     });
        // },
    //单个下发
    onSend: function(row,rescode) {
        if(row.id=="root"){
          this.$message.warning("该根节点数据不允许下发");
          return;
        }
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.sendForm.sendType = "single";
        this.singleSend = {};    
        let keyId = row.id;
        let version = row.version;
        let sendtoState = "DownAlready";
        let data = {"keyId":keyId,"version":version,"sendtoState":sendtoState};
        this.singleSend = data; 
        this.isSendEditForm = true;
    },

    refresh: function(){
        if (this.$refs['sendForm']) {
            this.$refs['sendForm'].resetFields();
        }
        this.sendForm.siteList = [];
        // alert(123);
    },

     // 提交下发界面数据
    comfirmSend: function (formName,rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        let dataList = [];//最终传给后台的总数据
        let siteListJson = [];//站点的数据
        for (let i=0;i<this.sendForm.siteList.length;i++){
            let siteId = this.sendForm.siteList[i];
            let resType = "AT";
            let state = "处理成功";
            let data = {"siteId":siteId,"resType":resType,"state":state};
            siteListJson.push(data);
        };
        if(this.sendForm.sendType=="batch"){           
            for(let i=0;i<this.multipleSelection.length;i++){
                let temp = this.multipleSelection[i];
                temp.siteList = siteListJson;
                dataList.push(temp);
            }
        }else if(this.sendForm.sendType=="single"){
            this.singleSend.siteList = siteListJson;
            dataList.push(this.singleSend);
        }
        this.$refs[formName].validate(function (valid) {
            if (valid) {
                _this.loading = true;
                _this.procCommand("MediaSendToProc",
                _this.modelName,
                "Default",
                {
                    "dataList":dataList,
                },
                null,
                _this.comfirmSendCallback);
            } else {
                return false;
            }
        });
    },
    // 执行命令后的回调函数
    comfirmSendCallback: function (isSuccess,json) {
        this.loading = false;
        if(isSuccess){
            this.isSendEditForm = false;
            this.$message({
                message: this.$i18n.t("message.successTip"),//resource.message.successTip,
                type: 'success'
            });
            this.queryTable();
        }
        else
        {
            this.$message({
                            message: json.msg,
                            type: 'warning'
                            });
        }
    },

     // 注销按钮
    logoffRow: function(node,data,rescode) {
        
        if(data.label=="资产分类"){
          this.$message({
                message: this.$i18n.t("该根节点数据不允许删除!"),
                type: 'warning'
          });
          return;
        }
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmlogoffMessage"), 
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": data.id, "version": data.version, isEnable: "Invalid" };
                    _this.loading = true;
                    _this.procCommand("PartialUpdateProc",//"ChangeIsEnabledState",
                            _this.modelName,
                            "N",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }
            }

            
        });
    },

    setEditFormCheck: function(){
      if(this.curCommand == "SaveNewReturnPK"){
          this.editFormCheck = [{
              key: "capitalCode",
              op: "=",
              val: this.editForm.capitalCode
          }
          // ,{
          //     key: "capitalName",
          //     op: "=",
          //     val: this.editForm.capitalName
          // }
          ];
      }else if(this.curCommand == "PartialUpdateProc"){
          this.editFormCheck = [{
              key: "capitalCode",
              group: "or",
              op: "=",
              val: this.editForm.capitalCode
          },
          // {
          //     key: "capitalName",
          //     group: "or",
          //     op: "=",
          //     val: this.editForm.capitalName
          // },
          {
              key: "keyId",
              op: "<>",
              val: this.editForm.keyId
          }];
      }
  },
    // getChildNode (row) {
    //   this.procCommand("QueryTreeDataProc",
    //         "com.ispr.iptv.entity.media.CapitalEntity",
    //         "Default",
    //         {
    //           "pCapitalCode":row.id,
    //         },
    //         null,
    //         this.setDataCallback);
    // },
    // expandNodeClick: function(row, node, self){
        
    //     this.current.row = row;
    //     this.current.node = node;
    //     this.procCommand("QueryTreeDataProc",
    //         "com.ispr.iptv.entity.media.CapitalEntity",
    //         "Default",
    //         {
    //           "pCapitalCode":row.id,
    //         },
    //         null,
    //         this.setDataCallback);
    // },

    setDataCallback: function(isSuccess,json) {
        this.loading = false;
        try{
            if (isSuccess) {
             
              //this.treeData = [];
              //this.treeData = json;

            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },
  //下发提示框
    // online(node, data) {
    //     this.isSendEditForm = true;
    // },
    // success: function(){
    //     this.isSendEditForm = false;
    //     this.$message({
    //             message: this.$i18n.t("message.successTip"),
    //             type: 'success'
    //     });
    //     this.queryTable();
    // },



    // remove(row) {

    //   // console.log("remove(node, data)==>", node, data);
    //   // const parent = node.parent;
    //   // const children = parent.data.children || parent.data;
    //   // const index = children.findIndex(d => d.id === data.id);
    //   // children.splice(index, 1);

    //   var _this = this;
    //   this.$confirm(
    //     this.$i18n.t("message.confirmDelMessage"),
    //     this.$i18n.t("message.confirmTitle"),
    //     {
    //       confirmButtonText: this.$i18n.t("message.yes"),
    //       cancelButtonText: this.$i18n.t("message.cancel"),
    //       type: "warning",
    //       callback: function(action, instance) {
    //         if (action == "confirm") {
    //           console.log("remove(node, data)==>", row);
    //           const parent = node.parent;
    //           const children = parent.data.children || parent.data;
    //           const index = children.findIndex(d => d.id === data.id);
    //           children.splice(index, 1);
    //         }
    //       }
    //     }
    //   );
    // },

    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button size="mini" type="text" on-click={() => this.add(data)}>
              Add
            </el-button>
            <el-button size="mini" type="text" on-click={() => this.edit(data)}>
              Edit
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              Delete
            </el-button>
          </span>
        </span>
      );
    },
    // 查询网格数据
    queryTable: function() {
        this.loading = true;
        this.procCommand("QueryTreeDataProc",
            "com.ispr.iptv.entity.media.CapitalEntity",
            "Default",
            {
              "pCapitalCode":"root"
            },
            null,
            this.setTableData);
    },

     //查询网格数据成功后的回调
    setTableData: function(isSuccess,json) {
        this.loading = false;
        try{
            if (isSuccess) {
                // alert(JSON.stringify(json));
                this.treeData = [];
                this.treeData = json;
                // for (var i = 0; i < json.data.length; i++) {
                //     this.treeData.push(json.list[i]);
                // }

            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },

    // 为状态下拉框赋值
    findEnables: function() {
        this.findByTypeCode("10001",this.setEnables)
    },
    // 查询状态下拉框数据成功后的回调
    setEnables: function(isSuccess,json) {
        try{
            if (isSuccess) {
                // this.enables = [];
                    console.info(json);
                for (var i = 0; i < json.data.length; i++) {
                    this.enables.push(json.data[i]);
                }
            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },

     //站点复选框数据 siteData
    findSite: function(){
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.Site",//修改为被查询的实体地址
                opKey: "Query",//后台编写相应的接口实现方法，主要负责转化类型
                params: [{key: 'isEnable',op: '=',val: 'Available'}],
                userInfo: this.getUserInfo()
            };
            var _this = this;
            this.axios.post('/api/query', queryRequest)
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    if (res.data.code == "SUCCESS") {
                        _this.siteData = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.siteData.push(res.data.data[i]);
                        }
                    } else {
                        // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    // this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
                });
    },





  },
   mounted: function mounted() {
    // this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
    // this.isInit = true;
    this.findSite();
    this.findEnables();
    this.onQuery();

  }
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  color: #333333;
}
</style>
